package com.dgut.springsecurity.Details;

import com.dgut.usermanager.entity.UserAccount;
import com.dgut.usermanager.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class UserAccountDetailService implements UserDetailsService {

    @Autowired
    private UserAccountService userAccountService;
    private boolean reachLimit = false;
    /*@Autowired
    UserDetailsManager userDetailsManager;*/


    public boolean isReachLimit() {
        return reachLimit;
    }

    public void setReachLimit(boolean reachLimit) {
        this.reachLimit = reachLimit;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAccount userAccount = userAccountService.findUserAccountByAccount(username);
        System.out.println("cadc");
        /*try {
            org.springframework.security.core.userdetails.User u=(org.springframework.security.core.userdetails.User)userDetailsManager.loadUserByUsername(username);
            return  u;
        }catch (UsernameNotFoundException e){*/
        if (!isReachLimit()) {
            if (userAccount == null)
                return new UserAccountDetail(new UserAccount(), AuthorityUtils.createAuthorityList("noADMIN"));
            else {
                System.out.println("cadc");
                return new UserAccountDetail(userAccount, AuthorityUtils.createAuthorityList(userAccount.getPower()));
            }
        }
        else{
            if (userAccount == null)
                return new UserAccountDetail(new UserAccount(), AuthorityUtils.createAuthorityList("noADMIN"));
            else {
                System.out.println("sdv");
                return new UserAccountDetail(userAccount, true, true, true, false, AuthorityUtils.createAuthorityList(userAccount.getPower()));
            }
        }

    /*public boolean setreachLimit(boolean limit){
        this.reachLimit=limit;
        return reachLimit;
    }*/

    }
}
